//
//  LoginViewController.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/5/17.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import SQLite

class LoginViewController: SCNTableViewController {
    
    typealias loginSuccess = () -> Void
    var loginAction: loginSuccess?
    

    lazy var headerImg: UIImageView = {
       
        let img = UIImageView()
        img.image = UIImage(named: "logo_login")
        return img
    }()
    lazy var nameL: UILabel = {
       
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 15.0)
        lab.textAlignment = .center
        lab.textColor = SCNConstants.colorWith255RGBA(37, g: 136, b: 229, a: 1)
        lab.text = "王大哥"
        return lab
    }()
    
    lazy var phoneTF: SCNLoginTextField = {
       
        let tf = SCNLoginTextField()
        tf.keyboardType = .numberPad
        tf.configuration(title: "手机号", placeholder: "请输入您的手机号")
        return tf
    }()
    lazy var pswTF: SCNLoginTextField = {
        let tf = SCNLoginTextField()
        tf.isSecureTextEntry = true
        tf.configuration(title: "密  码", placeholder: "请输入登录密码")

        return tf
    }()
    
    lazy var loginB: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = SCNConstants.rootBackgroundColor
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        btn.setTitle("登录", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.layer.cornerRadius = 5.0
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(login), for: .touchUpInside)
        return btn
    }()
    
    lazy var forgetB: UIButton = {
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        btn.setTitle("忘记密码", for: .normal)
        btn.setTitleColor(SCNConstants.rootBackgroundColor, for: .normal)
        btn.addTarget(self, action: #selector(forget), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "登录"
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "login_showview_cha_icon"), style: .plain, target: self, action: #selector(dismissViewController))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "注册", style: .plain, target: self, action: #selector(register))
        
        view.addSubview(headerImg)
        view.addSubview(nameL)
        view.addSubview(phoneTF)
        view.addSubview(pswTF)
        view.addSubview(loginB)
        view.addSubview(forgetB)
        
        headerImg.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(80)
            make.size.equalTo(CGSize(width: 70,height: 70))
        }
        nameL.snp.makeConstraints { (make) in
            make.top.equalTo(headerImg.snp.bottom)
            make.centerX.equalTo(view)
            make.size.equalTo(CGSize(width: SCNConstants.SCREENWIDTH - 100,height: 30))
        }
        phoneTF.snp.makeConstraints { (make) in
            make.top.equalTo(nameL.snp.bottom).offset(25)
            make.centerX.equalTo(view)
            make.size.equalTo(CGSize(width: SCNConstants.SCREENWIDTH - 20,height: 40))
        }
        pswTF.snp.makeConstraints { (make) in
            make.top.equalTo(phoneTF.snp.bottom).offset(15)
            make.centerX.equalTo(view)
            make.size.equalTo(CGSize(width: SCNConstants.SCREENWIDTH - 20,height: 40))
        }
        loginB.snp.makeConstraints { (make) in
            make.top.equalTo(pswTF.snp.bottom).offset(30)
            make.centerX.equalTo(view)
            make.size.equalTo(CGSize(width: SCNConstants.SCREENWIDTH - 20,height: 40))
        }
        forgetB.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 80,height: 25))
            make.top.equalTo(loginB.snp.bottom).offset(10)
            make.trailing.equalTo(loginB.snp.trailing)
        }
    }


    func dismissViewController() {
        self.dismiss(animated: true, completion: nil)
    }
    
    func register() {
        self.navigationController?.pushViewController(SCNRegisterViewController(), animated: true)
    }
    
    func login() {

        if let phone = phoneTF.text,let psw = pswTF.text {
            let params = ["mobile":phone,"pwd":psw,"device_token":String(UIDevice.current.systemName)]
            
            
            
            SCNRequestManager.postRequest(params, URL: SCNRequestAPI.menber().login) { [unowned self] (result) in
                
                self.loginAction?()
                
                NotificationCenter.default.post(name: Notification.Name.Login.LoginSuccess, object: nil)
               
                self.noticeSuccess("登录成功", autoClear: true, autoClearTime: 2)
               
                //清空之前账户
                SCNSQLiteManager().delTable()
                
                let value = result.result.value as? Dictionary<String, Any>
                let dataresult = value?["dataresult"] as? Dictionary<String, Any>
                let names = dataresult?["names"] as? Dictionary<String, Any>
                let memberid = dataresult?["memberid"] as! String
                let username = names?["username"] as! String
                let nickname = names?["nickname"] as! String
                let ico = names?["ico"] as! String
                var tree = ""
                if let tmp = names?["tree"] {
                    tree = "\(String(describing: tmp))"
                }
               
                let moblie = names?["moblie"] as! String
                
                let sqlManager = SCNSQLiteManager()
                //写入数据
                do {
                    _ = try sqlManager.db.run(sqlManager.userTable.insert(sqlManager.memberid <- memberid,sqlManager.username <- username,sqlManager.nickname <- nickname,sqlManager.ico <- ico,sqlManager.tree <- tree,sqlManager.moblie <- moblie))

                } catch {
                    printLog(error)
                }
                
                self.dismissViewController()
                

                
            }

        }
        
    }
    
    func forget() {
        self.navigationController?.pushViewController(SCNForgetPswViewController(), animated: true)
    }

}


